import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// 单个格子，函数
function Square(props) {
  return (
    /**接受输出 */
    <button className={ props.val ? (props.val.data1[0] === props.index || props.val.data1[1] === props.index || props.val.data1[2] === props.index ? 'cl square' : 'square') : 'square' } onClick={ props.onClick }>
      { props.value }
    </button>
  );
}

// 格子父级类
class Board extends React.Component {
  // 内部调用函数
  renderSquare(i) {
    return ( // 返回单格子航速以及方法
      // 接受父组件输出文字
      <Square
        key={ i }
        value={ this.props.squares[i] }
        val = {this.props.win}
        index = {i}
        onClick={ () => this.props.onClick(i) }
      />
    );
  }

  xxMethod(startIndex, endIndex) {
    let result = []
    for (let i = startIndex; i <= endIndex; i++) {
      result.push(this.renderSquare(i));
    } return result;
  }

  // 方法返回值，呈现于屏幕上的东西
  render() {
    const data = [{ key: 1, x: 0, y: 2 }, { key: 2, x: 3, y: 5 }, { key: 3, x: 6, y: 8 }]
    return (
      <div>
        {
          data.map(item => (
            <div key={ item.key } className="board-row">
              { this.xxMethod(item.x, item.y) }
            </div>
          ))
        }
      </div>
    );
  }
}

// 最高父级类（react.component是子集的意思）
class Game extends React.Component {
  // 构造函数
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true,
      arr: [],
      ys: 0,
      index: 0,
      negative: true
    };
  }

  // 点击函数
  handleClick(i) {
    // 获取数据
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    // 角色判断
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.state.arr.push(i + 1)

    this.setState({
      history: history.concat([
        {
          squares: squares
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext
    });
  }

  // 时间记忆
  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    

    // 时间记忆
    const moves = history.map((step, move) => {
    const index = this.state.arr[move - 1]
    const x = Math.ceil(index / 3)
    const y = index % 3 === 0 ? 3 : index % 3
    const desc = move ?
      'Go to move #' + move + " 坐标:" + (index ? "(" + x + ',' + y + ")" : '') :
      'Go to game start';

      return (
        <li className={ this.state.ys === move ? 'cl' : '' } key={ move }>
          <button className={ this.state.ys === move ? 'cl' : '' } onClick={ () => {
            this.jumpTo(move)
            this.setState({
              ys: move
            })
          } }>{ desc }</button>
        </li>
      );
    });

    if (!this.state.negative) {
      moves.sort().reverse();
    }


    let status;
    // 判断是否已有胜者，没有继续显示下一位
    if (winner) {
      status = "Winner: " + winner.data2;
    } else if (this.state.index >= 9) {
      status = "PlayEven：平局"
    } else {
      status = "Next player: " + (this.state.xIsNext ? "X" : "O");

    }

    // 根据升序降序给ol添加排序属性
    const rev = {};
    if (!this.state.negative) {
      rev['reversed'] = 'reversed'
    }

    // 调用board组件 传入数据 点击事件
    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={ current.squares }
            win = {winner}
            onClick={ i => {
              this.handleClick(i)
              this.setState({
                index: this.state.index+1
              })
            } }
          />
        </div>
        <div className="game-info">
          <div>{ status }</div>
          <ol {...rev}>{ moves }</ol>
        </div>
        <div>
          <button onClick={
            () => {
              this.setState({
                negative: !this.state.negative
              })

            }
          }>{this.state.negative ? '升序' : '降序'}</button>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(<Game />, document.getElementById("root"));

// 判断胜负
function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      // return squares[a];
      return {data1: lines[i] , data2: squares[a]}
    }
  }
  return null;
}